package com.changgou.order.controller;


import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;


import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/worder")
public class OrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * @param model
     * @return java.lang.String
     * @description: 购物车中商品展示
     * @author 大佬味的小男孩
     * @date 2020/08/03 15:05
     */
    @RequestMapping("/ready/order")
    public String readyOrder(Model model) {
        //收件人的地址信息
        List<Address> addressList = addressFeign.list().getData();
        model.addAttribute("address", addressList);

        //购物车信息
        Map map = cartFeign.list();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        Integer totalMoney = (Integer) map.get("totalMoney");
        Integer totalNum = (Integer) map.get("totalNum");

        model.addAttribute("carts", orderItemList);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute("totalNum", totalNum);

        //默认收件人信息
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())) {
                //默认收件人
                model.addAttribute("deAddr", address);
                break;
            }
        }
        return "order";
    }


    /**
     * @param order
     * @return com.changgou.entity.Result
     * @description: 生成订单
     * @author 大佬味的小男孩
     * @date 2020/08/03 15:06
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order) {
        Result result = orderFeign.add(order);
        return result;
    }

    /**
     * @param orderId
     * @param model
     * @return com.changgou.entity.Result
     * @description: 用于跳转支付页
     * @author 大佬味的小男孩
     * @date 2020/08/04 19:13
     */
    @GetMapping("toPayPage")
    public String toPayPage(@RequestParam("orderId") String orderId, Model model) {
        //根据订单id查询订单信息
        Result<Order> orderResult = orderFeign.findById(orderId);
        Order order = orderResult.getData();
        //Order order = (Order) orderFeign.findById(orderId).getData();

        model.addAttribute("orderId",orderId);
        model.addAttribute("payMoney",order.getPayMoney());
        return "pay";
    }

}
